<template>
  <div v-if="appInfo != null" class="app-detail">
    <!--    <el-drawer
          :close-on-click-modal="false"
          :with-header="false"
          custom-class="detail"
          v-model="visible"
          size="44%"
          :title="$t('common.detail')"
          v-loading="dataListLoading"
          @close="cancel">-->
    <el-page-header content="" @back="goToAppStore" />
    <div class="flex justify-between" style="margin: 20px 0px">
      <div class="flex">
        <img
          style="height: 110px; width: 110px;"
          :src="iconView(appInfo.appIconUrl)"
          @error="() => appInfo.appIconUrl = require('@/assets/img/Android.png')"
        >
        <div class="ml-4 mt-4">
          <h1 class="page-title">{{ appInfo.appName }}</h1>
          <p class="text-muted" style="color: #99a9bf">
            {{ $t('appstore.application.lastestVersionName') }}:
            {{ appInfo.lastestVersionName }}
          </p>
          <p class="text-muted" style="color: #99a9bf">
            {{ $t('appstore.application.developerName') }}:
            {{ appInfo.keyName }}
          </p>
        </div>
      </div>

      <div class="flex mr-12 ml-8">
        <!-- 分数分布 -->
        <div class="">
          <div class="flex items-center ml-4">
            <div class="mr-2 text-gray-500">
              5 <i class="el-icon-star-on active-star" />
            </div>
            <el-progress
              :percentage="calcPercent('5')"
              :show-text="false"
              style="width: 240px"
            />
            <span class="ml-2 text-gray-500">{{ scores['5'] }}</span>
          </div>
          <div class="flex items-center ml-4">
            <div class="mr-2 text-gray-500">
              4 <i class="el-icon-star-on active-star" />
            </div>
            <el-progress
              :percentage="calcPercent('4')"
              :show-text="false"
              style="width: 240px"
            />
            <span class="ml-2 text-gray-500">{{ scores['4'] }}</span>
          </div>
          <div class="flex items-center ml-4">
            <div class="mr-2 text-gray-500">
              3 <i class="el-icon-star-on active-star" />
            </div>
            <el-progress
              :percentage="calcPercent('3')"
              :show-text="false"
              style="width: 240px"
            />
            <span class="ml-2 text-gray-500">{{ scores['3'] }}</span>
          </div>
          <div class="flex items-center ml-4">
            <div class="mr-2 text-gray-500">
              2 <i class="el-icon-star-on active-star" />
            </div>
            <el-progress
              :percentage="calcPercent('2')"
              :show-text="false"
              style="width: 240px"
            />
            <span class="ml-2 text-gray-500">{{ scores['2'] }}</span>
          </div>
          <div class="flex items-center ml-4">
            <div class="mr-2 text-gray-500">
              1 <i class="el-icon-star-on active-star" />
            </div>
            <el-progress
              :percentage="calcPercent('1')"
              :show-text="false"
              style="width: 240px"
            />
            <span class="ml-2 text-gray-500">{{ scores['1'] }}</span>
          </div>
        </div>

        <div class="flex items-center">
          <div
            style="
              border-left: solid 1px #d9e2e9;
              margin-left: 50px;
              padding-left: 50px;
              height: 70px;
            "
          />
        </div>

        <!-- 评分 -->
        <div class="flex flex-col self-center">
          <div class="text-center mb-1">
            <div style="font-size: 40px; line-height: 40px; font-weight: 900">
              {{ sumStar }}
            </div>
            <div class="mt-2">
              <i
                v-for="n in 5"
                class="el-icon-star-on"
                :class="[n <= sumStar ? 'active-star' : 'inactive-star']"
              />
            </div>
          </div>
        </div>
      </div>
      <div>
        <div class="flex">
          <div class="mini-tag">
            <div class="mini-tag-label">
              {{ $t('appstore.application.appSize') }}
            </div>
            <div class="mini-tag-content" style="">
              {{ appInfo.appSize }} MB
            </div>
          </div>
          <div class="mini-tag">
            <div class="mini-tag-label">
              {{ $t('appstore.application.status') }}
            </div>
            <div
              class="mini-tag-content"
              style=""
            >
              {{ handleStatus(appInfo) }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane :label="$t('common.detail')" name="first">
        <el-descriptions
          v-loading="dataListLoading"
          direction="vertical"
          class="margin-top"
          title=""
          :column="12"
          size="60"
          border
        >
          <template #extra/>
          <el-descriptions-item
            :label="$t('appstore.application.appName')"
            :span="3"
          >
            {{ appInfo.appName }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.lastestVersionName')"
            :span="3"
          >
            {{ appInfo.lastestVersionName }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.categoryName')"
            :span="3"
          >
            {{ appInfo.categoryName }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.packageName')"
            :span="3"
          >
            {{ appInfo.packageName }}
          </el-descriptions-item>
          <!--          <el-descriptions-item :label="$t('appstore.application.releaseTarget')" :span="3">-->
          <!--            <div v-if="appInfo.releaseTarget == 1">{{ $t('appstore.application.releaseTarget1') }}</div>-->
          <!--            <div v-if="appInfo.releaseTarget == 2">{{ $t('appstore.application.releaseTarget2') }}</div>-->
          <!--            <div v-if="appInfo.releaseTarget == 3">{{ $t('appstore.application.releaseTarget3') }}</div>-->
          <!--          </el-descriptions-item>-->
          <el-descriptions-item
            :label="$t('appstore.application.developerName')"
            :span="3"
          >
            {{ appInfo.developerName }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.support_device_type')"
            :span="3"
          >
            <el-tag
              v-if="appInfo.landscape === 1"
              style="margin-left: 5px"
              size="small"
            >{{ $t('appstore.application.landscape') }}</el-tag>
            <el-tag
              v-if="appInfo.portrait === 1"
              style="margin-left: 5px"
              size="small"
            >{{ $t('appstore.application.portrait') }}</el-tag>
          </el-descriptions-item>
          <!--          <el-descriptions-item :label="$t('appstore.application.bankcardApp')" :span="3">-->
          <!--            <el-checkbox v-model="appInfo.bankcardApp === 1" disabled>{{ $t('appstore.application.bankcardApp') }}-->
          <!--            </el-checkbox>-->
          <!--          </el-descriptions-item>-->
          <!--          <el-descriptions-item :label="$t('appstore.application.highQuality')" :span="3">-->
          <!--            <el-checkbox v-model="appInfo.highQuality === 1" disabled>{{ $t('appstore.application.highQuality') }}-->
          <!--            </el-checkbox>-->
          <!--          </el-descriptions-item>-->
          <el-descriptions-item
            :label="$t('appstore.application.mainLanguage')"
            :span="3"
          >
            <!--            <el-select v-model="appInfo.mainLanguage" size="small" disabled>-->
            <!--              <el-option-->
            <!--                v-for="lang in langList"-->
            <!--                :key="lang.val"-->
            <!--                :value="lang.val"-->
            <!--                :label="lang.label"-->
            <!--              />-->
            <!--            </el-select>-->
            <el-tag size="small">{{
              $t('language_list.' + appInfo.mainLanguage)
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.supportLanguage')"
            :span="3"
          >
            <!--            <el-select-->
            <!--              v-model="appInfo.supportLanguage"-->
            <!--              multiple-->
            <!--              disabled-->
            <!--              default-first-option-->
            <!--              filterable-->
            <!--              style="width: 100%"-->
            <!--            >-->
            <!--              <el-option-->
            <!--                v-for="lang in langList"-->
            <!--                :key="lang.id"-->
            <!--                :value="lang.val"-->
            <!--                :label="lang.label"-->
            <!--              />-->
            <!--            </el-select>-->
            <div style="line-height: 2.4">
              <el-tag
                v-for="language in appInfo.supportLanguage"
                :key="language"
                style="margin-left: 5px"
                size="small"
              >{{ $t('language_list.' + language) }}</el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.creTime')"
            :span="3"
          >
            {{ formatDate(appInfo.creTime) }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.updTime')"
            :span="3"
          >
            {{ formatDate(appInfo.updTime) }}
          </el-descriptions-item>

        </el-descriptions>

        <!-- 多语言 -->
        <div
          class="language-block"
          style="border: 1px solid #eeeeee; border-radius: 6px; margin-top: 16px; margin-bottom: 16px; "
        >

          <div
            v-for="(obj, index) in appInfo.appLanguageInfos"
            :key="obj.language"

            class="text-gray-500 px-4 language-block__item"
          >
            <div
              class="flex justify-between items-center"
              role="button"
              @click="showLanguageInfo(index)"
            >
              <div style="padding: 16px 0;">{{ $t('language_list.'+ obj.language) }}</div>
              <div class="flex flex-center">
                <i
                  class="el-icon-arrow-right mr-3 transition-all ml-5"
                  :class="{'transform rotate-90': obj.isActive}"
                />
              </div>
            </div>

            <el-descriptions v-if="obj.isActive" style="padding-bottom: 16px;" :column="1" border>
              <el-descriptions-item label-style="width: 200px">
                <template #label>{{ $t('appstore.application.appIntroduction') }}</template>
                <div class="html-container">

                  <div style="padding: 12px;" v-html="obj.introduction" />
                </div>
              </el-descriptions-item>
              <el-descriptions-item label-style="width: 200px" :label="$t('appstore.application.revision')">
                <div class="html-container">
                  <div style="padding: 12px;" v-html="obj.revision" />
                </div>
              </el-descriptions-item>
              <el-descriptions-item v-if="landscapePicUrls.length || portraitPicUrls.length" label-style="width: 200px">
                <template #label>{{ $t('appstore.application.screenshots') }}</template>
                <div>
                  <div style="text-align: center;padding: 8px;">
                    <el-radio v-model="screenshotType" :label="1" :disabled="!landscape">
                      {{ $t('appstore.application.horizontalScreenshot') }}
                    </el-radio>
                    <el-radio v-model="screenshotType" :label="2" :disabled="!portrait">
                      {{ $t('appstore.application.verticalScreenshot') }}
                    </el-radio>
                  </div>
                  <el-carousel v-if="screenshotType === 1" :interval="4000" type="card" height="214px">
                    <el-carousel-item v-for="img in landscapePicUrls" :key="img.url">
                      <h3 class="medium">
                        <el-image
                          :src="baseApiUrl + img.url"
                          :preview-src-list="getImgList(landscapePicUrls)"
                        />
                      </h3>
                    </el-carousel-item>
                  </el-carousel>

                  <el-carousel v-else-if="screenshotType === 2" :interval="4000" type="card" height="380px">
                    <el-carousel-item v-for="img in portraitPicUrls" :key="img.url">
                      <h3 class="small">
                        <el-image :src="baseApiUrl + img.url" :preview-src-list="getImgList(portraitPicUrls)" />
                      </h3>
                    </el-carousel-item>
                  </el-carousel>

                  <div v-else class="data-empty">
                    <icon-svg class="data-empty-icon" name="chart-data-empty" />
                    <div class="data-empty-text">{{ $t('common.noData') }}</div>
                  </div>
                </div>
              </el-descriptions-item>
            </el-descriptions>

          </div>
        </div>

      </el-tab-pane>
      <el-tab-pane
        :label="$t('appstore.application.appVersionList')"
        name="second"
      >
        <AppVersion
          ref="appVersion"
          @close="getData()"
          @refreshData="getData()"
        />
      </el-tab-pane>
      <el-tab-pane
        :label="$t('appstore.application.appRevisionList')"
        name="third"
      >
        <AppRevision ref="appRevision" />
      </el-tab-pane>
      <el-tab-pane
        :label="$t('appstore.application.appDownloadList')"
        name="fourth"
      >
        <AppDownload ref="appDownload" />
      </el-tab-pane>
      <el-tab-pane
        :label="$t('appstore.application.appAppraiseList')"
        name="sixth"
      >
        <AppAppraise ref="appAppraise" />
      </el-tab-pane>
    </el-tabs>
    <!--    </el-drawer>-->
  </div>
</template>

<script>
import {
  getAppInfo,
  screenshotList,
  updateHighQualityStatus,
  getAppScores
} from '@/api/developer-app'
import { formatDate } from '@/utils/formatDate'
import AppVersion from './app-version'
import AppRevision from './app-revision'
import AppDownload from './app-download'
import AppAppraise from './app-appraise'

var blockFun = function() {
  // 兼容处理
  var target = event.target || event.srcElement
  // 判断是否匹配目标元素
  if (target.nodeName.toLocaleLowerCase() === 'a') {
    console.log('当前点击的 a 标签: ', target)

    // 对捕获到的 a 标签进行处理，需要先禁止它的跳转行为
    if (event.preventDefault) {
      event.preventDefault()
    } else {
      window.event.returnValue = true
    }

    // 处理完 a 标签的内容，重新触发跳转，根据原来 a 标签页 target 来判断是否需要新窗口打开

    var url = target.getAttribute('href')
    if (target.getAttribute('target') === '_blank') {
      window.goRoute(url)
    } else {
      window.location.href = url
    }
  }
}

export default {
  components: {
    AppVersion,
    AppRevision,
    AppDownload,
    AppAppraise
  },
  data() {
    return {
      appLanguageInfos: [],
      baseApiUrl: import.meta.env.VITE_APP_BASE_API,
      portrait: false,
      portraitPicUrls: [],
      landscape: false,
      landscapePicUrls: [],
      sumStar: 0,
      scores: {
        1: 0,
        2: 0,
        3: 0,
        4: 0,
        5: 0
      },
      appId: 0,
      appVersionId: 0,
      appInfo: null,
      appAgreement: '',
      screenshotType: 1,
      screenshots_h: [],
      screenshots_v: [],
      activeName: 'first',
      dataListLoading: false,
      agreementLoading: false,
      tempEnlargedPicture: [],
      langList: [
        { val: 'zh_CN', label: this.$t('language_list.zh_CN') },
        { val: 'en_US', label: this.$t('language_list.en_US') },
        { val: 'ko', label: this.$t('language_list.ko') },
        { val: 'jp', label: this.$t('language_list.jp') },
        { val: 'pt', label: this.$t('language_list.pt') },
        { val: 'ru', label: this.$t('language_list.ru') },
        { val: 'fr', label: this.$t('language_list.fr') },
        { val: 'de', label: this.$t('language_list.de') },
        { val: 'es', label: this.$t('language_list.es') },
        { val: 'it', label: this.$t('language_list.it') },
        { val: 'ar', label: this.$t('language_list.ar') },
        { val: 'other', label: this.$t('language_list.other') }
      ]
    }
  },
  computed: {},
  mounted() {
    window.goRoute = this.goRoute
    document.body.addEventListener('click', blockFun)
    this.activeName = 'first'
    this.dataListLoading = true
    this.appId = this.$route.query.appId
    this.appVersionId = this.$route.query.appVersionId
    this.getData()
    this.getAppScores()
    /*  this.agreementLoading = true
    getAppAgreement(this.appId).then(data => {
      this.appAgreement = data
      this.agreementLoading = false
    }).catch(e => {
      console.log(`err:${JSON.stringify(e)}`)
      this.agreementLoading = false
    }) */
  },
  destroyed() {
    document.body.removeEventListener('click', blockFun)
  },
  methods: {
    getImgList(list) {
      const ret = []
      for (const url of list) {
        ret.push(import.meta.env.VITE_APP_BASE_API + url.url)
      }
      return ret
    },
    goRoute(url) {
      const encodeUri = encodeURIComponent(url)
      const routeUrl = this.$router.resolve({
        path: '/out-link',
        query: { target: encodeUri }
      })
      window.open(routeUrl.href, '_blank')
    },
    showLanguageInfo(index) {
      this.appInfo.appLanguageInfos.map((item) => (item.isActive = false))
      this.landscapePicUrls = this.appInfo.appLanguageInfos[index].applicationScreenshotList.filter(v => {
        return v.screenType === 1
      })
      this.portraitPicUrls = this.appInfo.appLanguageInfos[index].applicationScreenshotList.filter(v => {
        return v.screenType === 2
      })
      this.appInfo.appLanguageInfos[index].isActive = true
    },
    getAppScores() {
      getAppScores(this.appId)
        .then((res) => {
          this.scores = res
        })
        .catch((e) => this.$confirmError(e))
    },
    calcPercent(key) {
      let sum = 0
      Object.keys(this.scores).forEach((item) => {
        sum += this.scores[item]
      })
      if (sum !== 0) {
        return ((this.scores[key] * 100) / sum).toFixed(0)
      }
      return 0
    },
    showEnlargedPicture(url) {
      url = this.iconView(url)
      this.tempEnlargedPicture.length = 0
      this.tempEnlargedPicture.push(url)
    },
    handleStatus(appInfo) {
      if (appInfo.status === 11) {
        return this.$t('developer_app.status_option[0].label')
      } else if (appInfo.status === 9) {
        return this.$t('developer_app.status_option[1].label')
      } else if (appInfo.status === 7) {
        return this.$t('developer_app.status_option[2].label')
      } else if (appInfo.status === 6) {
        return this.$t('developer_app.status_option[3].label')
      } else if (appInfo.status === 5) {
        return this.$t('developer_app.status_option[4].label')
      } else if (appInfo.status === 1) {
        if (appInfo.forceSuspendReason) {
          return this.$t('developer_app.status_option[7].label')
        } else {
          return this.$t('developer_app.status_option[5].label')
        }
      } else if (appInfo.status === 0) {
        return this.$t('developer_app.status_option[6].label')
      }
    },
    goToAppStore() {
      this.$router.back()
    },
    iconView(icon) {
      if (icon) {
        return import.meta.env.VITE_APP_BASE_API + icon
        // return icon
      }
      return require('@/assets/img/Android.png')
    },
    updateHighQualityStatus() {
      let params = {}
      if (this.appInfo.highQuality === 1) {
        params = { highQualityStatus: 0 }
      } else if (this.appInfo.highQuality === 0) {
        params = { highQualityStatus: 1 }
      }
      updateHighQualityStatus(this.appId, params)
        .then((data) => {
          if (data && data === 1) {
            this.$message.success(this.$t('common.operate_success'))
            this.dataListLoading = true
            getAppInfo(this.appId)
              .then((data) => {
                this.appInfo = data
                this.dataListLoading = false
              })
              .catch((e) => {
                this.$confirmError(e)
                console.log(`err:${JSON.stringify(e)}`)
                this.dataListLoading = false
              })
          } else {
            this.$message.error(data.message)
          }
        })
        .catch((e) => {
          this.$confirmError(e)
          this.dataListLoading = false
          console.log(`err:${JSON.stringify(e)}`)
        })
    },
    errorHandler() {
      return true
    },
    handleClick(tab, event) {
      if (tab.name === 'first') {
        this.getData()
      } else if (tab.name === 'second') {
        this.$nextTick(() => {
          this.$refs.appVersion.init(this.appId)
        })
      } else if (tab.name === 'third') {
        this.$nextTick(() => {
          this.$refs.appRevision.init(this.appId)
        })
      } else if (tab.name === 'fourth') {
        this.$nextTick(() => {
          this.$refs.appDownload.init(this.appId)
        })
      } else if (tab.name === 'fifth') {
        this.$nextTick(() => {
          this.$refs.appPurchase.init(this.appId)
        })
      } else if (tab.name === 'sixth') {
        this.$nextTick(() => {
          this.$refs.appAppraise.init(this.appId)
        })
      }
    },
    formatDate(value) {
      return formatDate(value, 'YYYY-MM-DD HH:mm:ss')
    },
    getData() {
      getAppInfo(this.appId)
        .then(async(data) => {
          this.dataListLoading = false
          this.appInfo = data
          // 将主语言置顶
          const index = this.appInfo.supportLanguage.findIndex(v => {
            return v === this.appInfo.mainLanguage
          })
          if (index > -1) {
            this.appInfo.supportLanguage.splice(index, 1)
          }
          this.appInfo.supportLanguage.splice(0, 0, this.appInfo.mainLanguage)

          this.landscape = this.appInfo.landscape
          this.portrait = this.appInfo.portrait

          if (this.landscape) {
            this.screenshotType = 1
          } else if (this.portrait) {
            this.screenshotType = 2
          }
          await screenshotList(this.appId, {
            appVersionId: this.appVersionId,
            screenType: 1
          }).then(data => {
            this.screenshots_h = data
          }).catch(e => {
            this.$confirmError(e)
            console.log(`err:${JSON.stringify(e)}`)
          })
          await screenshotList(this.appId, {
            appVersionId: this.appVersionId,
            screenType: 2
          }).then(data => {
            this.screenshots_v = data
          }).catch(e => {
            this.$confirmError(e)
            console.log(`err:${JSON.stringify(e)}`)
          })
          this.appLanguageInfos = []
          // 图片插入到一个列表中
          this.appInfo.supportLanguage.forEach((l) => {
            const langObj = { language: l, introduction: '', applicationScreenshotList: [] }
            const himg = this.screenshots_h.find(s => {
              return s.language === l
            })
            if (himg) {
              langObj.introduction = himg.introduction
              langObj.revision = himg.revision
              langObj.applicationScreenshotList = langObj.applicationScreenshotList.concat(himg.applicationScreenshotList)
            }
            const vimg = this.screenshots_v.find(s => {
              return s.language === l
            })
            if (vimg) {
              langObj.applicationScreenshotList = langObj.applicationScreenshotList.concat(vimg.applicationScreenshotList)
            }
            this.appLanguageInfos.push(langObj)
            console.log(langObj)
          })
          this.appInfo.appLanguageInfos = []
          // 置顶主语言，并 active
          this.appLanguageInfos.forEach(v => {
            v.applicationScreenshotList.forEach(img => {
              img.url = img.url + '?t=' + new Date().getTime()
            })
            if (v.language === this.appInfo.mainLanguage) {
              this.appInfo.appLanguageInfos.splice(0, 0, { ...v, isActive: true })
              this.landscapePicUrls = v.applicationScreenshotList.filter(img => {
                return img.screenType === 1
              })

              this.portraitPicUrls = v.applicationScreenshotList.filter(obj => {
                return obj.screenType === 2
              })
            } else {
              this.appInfo.appLanguageInfos.push({ ...v, isActive: false })
            }
          })
          this.dataListLoading = false
          this.sumStar = data.scoreAverage || 0
        })
        .catch((e) => {
          this.$confirmError(e)
          console.log(`err:${JSON.stringify(e)}`)
          this.dataListLoading = false
        })
    }
  }
}
</script>

<style lang="scss" scoped>

.html-container {
  ::v-deep a{
    color: #3F9EFF;
    text-decoration: underline;
  }
  ::v-deep blockquote {
    border-left: solid 4px #eeeeee;
    padding-left: 16px;
  }
  ::v-deep h1,h2,h3,h4,h5,h6 {
    font-weight: 600;
  }

  ::v-deep h1 {
    font-size: 40px;
  }

  ::v-deep h2 {
    font-size: 32px;
  }

  ::v-deep h3 {
    font-size: 28px;
  }

  ::v-deep h4 {
    font-size: 24px;
  }
  ::v-deep h5 {
    font-size: 20px;
  }
  ::v-deep h6 {
    font-size: 16px;
  }
}

.language-block__item {
  border-top: 1px solid #eeeeee;;
}

.language-block__item:first-child{
  border-top: none;
}

</style>

<style lang="scss">
.active-star {
  color: #e6a33b;
}
.inactive-star {
  color: #b7b7b7;
}

.mini-tag {
  margin: 12px;
  .mini-tag-label {
    border-radius: 6px 6px 0 0;
    background-color: #2b7ae2;
    text-align: center;
    color: #fff;
    font-size: 14px;
    padding: 4px 10px;
  }
  .mini-tag-content {
    font-weight: 500;
    text-align: center;
    font-size: 16px;
    border-radius: 0 0 6px 6px;
    padding: 4px 10px;

    border: solid 1px #e0e0e0;
  }
}
.separator {
  float: right;
  margin: 50%;
  font-weight: 700;
  color: #c0c4cc;
}
</style>
